package org.canaan.http.urlpair.resolver.impl;


import org.canaan.http.urlpair.core.Utils;
import org.canaan.http.urlpair.resolver.UrlPairResolver;

import java.util.Map;
import java.util.TreeMap;

/**
 * 数组解析
 * @author Canaan
 * @date 2017/6/29 0029
 */
public class ArrayListResolver implements UrlPairResolver {
    @Override
    public boolean resolvable(Object o) {
        return o != null && o.getClass().isArray();
    }

    @Override
    public String resolve(String key, Object value) {
        Object[] arr = (Object[]) value;

        if (arr.length == 0) {
            return key + "[]=";
        }

        Map<String, Object> map = new TreeMap<>();
        int index = 0;
        for (Object obj : arr) {
            String _key = key + "[" + index + "]";
            if (Utils.isBaseType(obj)) {
                map.put(_key, Utils.urlEncoder(obj));
            }else{ //处理一个非基本类型的对象
                ResolveUtils.resolveObject(_key,obj,map);
            }
            index++;
        }

        StringBuilder sb = new StringBuilder();
        for (String _key : map.keySet()) {
            sb.append(_key).append("=").append(map.get(_key)).append("&");
        }
        if (sb.length()>0)
            sb.deleteCharAt(sb.length() - 1);

        return sb.toString();
    }

}
